using System;
using System.IO;
using System.Net;
using System.Xml;

namespace CodeBackpack.Plist
{
    internal class EmbeddedDtdResolver : XmlResolver
    {
        public override Uri ResolveUri(Uri baseUri, String relativeUri)
        {
            if (relativeUri == PropertyListXmlWriter.DtdPubid)
            {
                return new Uri(PropertyListXmlWriter.DtdSysid);
            }
            else
            {
                return base.ResolveUri(baseUri, relativeUri);
            }
        }

        public override object GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
        {
            if (absoluteUri.ToString() == PropertyListXmlWriter.DtdSysid)
            {
                return GetEmbeddedResource(GetType(), "PropertyList-1.0.dtd");
            }
            else
            {
                return null;
            }
        }

        public override ICredentials Credentials
        {
            [NoTestCoverage]
            set { }
        }

        [NoTestCoverage]
        private static Stream GetEmbeddedResource(Type type, string resourceName)
        {
            Stream stream = type.Assembly.GetManifestResourceStream(type, resourceName);
            if (stream == null)
            {
                throw new ArgumentException(
                    String.Format("Embedded resource '{0}.{1}' is not found!", type.Namespace, resourceName));
            }
            return stream;
        }
    }
}